const utils = require('../../utils/util.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    applyUid: 0,
    license: [],//营业执照
    showLicense: [],//渲染营业执照
    idCardPosi: [],//身份证正面
    showIdCardPosi: [],
    idCrdRe: [],//身份证背面
    showIdCrdRe: [],//
    otherPhoto: [],//其他证件
    showOtherPhoto: [],
    bankId: '',
    pic: 1, //1 营业执照,2 身份证正面,3 身份证背面,4 其他证件,5 门头照, 6 店内照片
    isEditor: false,
    isSelf: true,
    remark: '',  
    applymentMsg: '',
    industry: '请选择行业',
    range: ['小吃熟食', '饮品甜品', '烘焙糕点', '火锅', '烧烤', '西餐','中餐', '自助餐', '中餐地方菜', '异域料理', '其他'],
    citys: [],
    cityList: [],
    provinces: [],
    countys:[],
    selProvince: '请选择省',
    selCity: '请选择市',
    selCounty: '请选择区县',  //区县
   
    branchBankList: [],
    branchBank: '请选择开户支行',
    bankName: '请选择开户银行',
    bankList: [],    
    payState : 0,
    bankMode: 0,      //银行卡输入方式: 0 选择方式, 1 手动输入
    adminMobile: '',  //微信管理员手机号
    adminEmail: '',   //微信管理员邮箱

    storeName:'',  //支付宝店铺名
    name: '',     //支付宝姓名
    account: '',  //支付宝账号
    mobile: '',   //支付宝手机号
    email: '',    //支付宝email
    address: '',  //支付宝地址
    headImg: [],      //支付宝门头照
    showHeadImg: [],  //支付宝门头照
    shopImgs:[],      //支付宝门店照片
    showShopImgs: [], //支付宝门店照片
    tab: 0  // 1 显示微信信息, 2 显示支付宝信息
  },

 //获取省
  getProvince: function (selProvince) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Tool/ProvinceList',
      success: function (res) {
        var provincesArray = JSON.parse(res.data.Data)
        var pinkArray = [];
        for (var i = 0; i < provincesArray.length; i++) {
          pinkArray.push(provincesArray[i].name);
          if (provincesArray[i].name == selProvince && selProvince != "请选择省") {
            that.getCityList(i + 1);
          }
        }
        that.setData({
          provinces: pinkArray
        })
      }
    })
  },
  //省值选择变化
  bindProvince: function (e) {
    var selIterm = this.data.provinces[e.detail.value];
    var provinceId = parseInt(e.detail.value) + 1;
    this.setData({
      selProvince: selIterm,
    })
    this.getCityList(provinceId) //初始化市数据
  },
  //获取市
  getCityList: function (provinceid) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Tool/CityList?provinceId=' + provinceid,
      success: function (res) {
        var cityList = JSON.parse(res.data.Data)
        var citys = [];
        for (var i = 0; i < cityList.length; i++) {
          citys.push(cityList[i].name);
        }
        that.setData({
          citys: citys,
          cityList: cityList,
          selCity: citys[0],
          countys: [],
          selCounty:'请选择区县'
        })   
      }
    })
  },
  //市值选择
  bindCity: function (e) {
    var cityList = this.data.cityList;
    var selIterm = this.data.citys[e.detail.value];
    var cityId = 0;
    for (var i = 0; i < cityList.length; i++) {
      if (selIterm == cityList[i].name) {
        cityId = cityList[i].id
      }
    }
    this.setData({
      selCity: selIterm,
    })
    if(this.data.tab == 1){
      this.getBankList(selIterm);    
    }
    if(this.data.tab == 2){
      this.getCountyList(cityId);
    }
  },
  //获取区县
  getCountyList: function (cityId) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Tool/CountyList?cityId=' + cityId,
      success: function (res) {
        var data = JSON.parse(res.data.Data)
        var list = [];
        for (var i = 0; i < data.length; i++) {
          list.push(data[i].name);
        }
        that.setData({
          countys: list,
          selCounty: list[0]
        })   
      }
    })
  },
  //绑定区县
  bindCounty: function (e) {
    var selCounty = this.data.countys[e.detail.value];
    this.setData({
      selCounty: selCounty
    })    
  },

  // 开户银行
  getBankList: function (city) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/tool/GetBankTypelist?city=' + city,
      success: function (res) {        
        if (res.data.Data.length > 0) {
          var bankList = res.data.Data;
          bankList.splice(0,0,'手动输入');
          that.setData({
            bankList: bankList
          })
        }
      }
    })
  },
  // 开户支行
  getBranchList: function (bankName) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/tool/GetBankList?bank=' + bankName + '&city=' + that.data.selCity,
      success: function (res) {
        if (res.data.Data.length > 0) {
          that.setData({
            branchBankList: res.data.Data
          })
        }
      }
    })
  },
  bindBankid: function (e) {
    this.setData({
      bankId: e.detail.value
    })
  },
  //支行名称
  bindBranchBank: function (e) {
    let that = this;
    let range = that.data.branchBankList;
    that.setData({
      branchBank: range[e.detail.value]
    })
  },
  //支行名称：手动输入
  bindCusBranchBank: function (e) {
    this.setData({
      branchBank: e.detail.value
    })
  },
  //银行名称
  bindBankName: function (e) {
    let that = this;
    let index = e.detail.value;
    let range = that.data.bankList; 
    that.setData({
      bankName: range[index],
      branchBankList: [],
      bankMode: index==0  ? 1 : 0
    })
    if(that.data.bankMode ==0){
      that.getBranchList(range[index]);
    }    
  },
  bindAccount: function (e) {
    this.setData({
      account: e.detail.value
    })
  },
  bindName: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  bindMobile: function (e) {
    this.setData({
      mobile: e.detail.value
    })
  },
  bindEmail: function (e) {
    this.setData({
      email: e.detail.value
    })
  },
  bindAdminMobile: function (e) {
    this.setData({
      adminMobile: e.detail.value
    })
  },
  bindAdminEmail: function (e) {
    this.setData({
      adminEmail: e.detail.value
    })
  },
  bindIndustry: function (e) {
    let that = this;
    let range = that.data.range;
    that.setData({
      industry: range[e.detail.value]
    })
  },
  bindRemark: function (e) {
    this.setData({
      remark: e.detail.value
    })
  },
  bindStoreName: function (e) {
    this.setData({
      storeName: e.detail.value
    })
  },
  bindAddress: function (e) {
    this.setData({
      address: e.detail.value
    })
  },
  //微信申请
  apply: function () {
    if(this.data.tab == 1){
      this.wxApply();
    }
    if(this.data.tab == 2){
      this.alipayApply();
    }
  },
  //微信申请
  wxApply: function () {
    let that = this; 
    if(that.data.payState ==1 ){
      utils.showModal('已审核后不允许更改'); return;
    }
    if (that.data.license.length == 0) {
      utils.showModal('请上传营业执照'); return;
    }
    if (that.data.idCardPosi.length == 0) {
      utils.showModal('请上传身份证正面'); return;
    }
    if (that.data.idCrdRe.length == 0) {
      utils.showModal('请上传身份证反面'); return;
    }
 
    if (!that.data.branchBank || that.data.branchBank == '请选择开户支行' || !that.data.bankId) {
      utils.showModal('请填写银行卡信息'); return;
    }
    if (that.data.industry == '' || that.data.industry == '请选择行业') {
      utils.showModal('请选择经营类目'); return;
    }
    if (!that.data.adminMobile) {
      utils.showModal('请填写手机号'); return;
    }
    if (!that.data.adminEmail) {
      utils.showModal('请填写管理员邮箱'); return;
    }    
    let AgentCheckState = 0;
    if (!that.data.isSelf) {//不是自己是代理商
      AgentCheckState = 1;
    }
    let otherPhoto = that.data.otherPhoto.join(','); 
    let data = {
      Uid: that.data.applyUid,
      License: that.data.license[0],
      IdCard: that.data.idCardPosi[0],
      IdCardReverse: that.data.idCrdRe[0],
      BankName: that.data.branchBank,
      BankNumber: that.data.bankId,
      OtherLicense: otherPhoto,
      AgentCheckState: AgentCheckState,
      Remark: that.data.remark,
      Industry: that.data.industry,
      City: that.data.selCity,      
      AdminMobile: that.data.adminMobile,
      AdminEmail: that.data.adminEmail,
    }
    wx.request({
      url: app.globalData.host + '/api/Coupon/SetCardApply',
      data: data,
      method: 'POST',
      success: function (res) {
        if (res.data.Code == 0) {
          utils.showToast('提交成功');
          setTimeout(() => {
            wx.navigateBack({delta: 1})
          }, 1000);
        }else{
          utils.showModal(res.data.Message);
        }
      }
    })  
  },
  //支付宝申请
  alipayApply: function () {
    let that = this;
    if(that.data.payState ==1 ){
      utils.showModal('已审核后不允许更改'); return;
    }
    if (that.data.license.length == 0) {
      utils.showModal('请上传营业执照'); return;
    }      
    if (that.data.industry == '' || that.data.industry == '请选择行业') {
      utils.showModal('请选择经营类目'); return;
    }   
    if (that.data.selCounty == '' || that.data.selCounty == '请选择区县') {
      utils.showModal('请选择区县'); return;
    }
    if (!that.data.address) {
      utils.showModal('请填写店铺地址'); return;
    }
    if (!that.data.storeName) {
      utils.showModal('请填写店铺名称'); return;
    }
    if (!that.data.account) {
      utils.showModal('请填写支付宝账号'); return;
    }
    if (!that.data.name) {
      utils.showModal('请填写姓名'); return;
    }
    if (!that.data.mobile) {
      utils.showModal('请填写手机号'); return;
    }
    if (!that.data.email) {
      utils.showModal('请填写邮箱'); return;
    }          
  
    var data ={
      uid: that.data.applyUid,
      account: that.data.account,
      name: that.data.name,
      storeName: that.data.storeName,
      mobile: that.data.mobile,
      email: that.data.email,
      industry: that.data.industry,
      license: that.data.license[0],
      headImg: that.data.headImg[0],
      shopImgs: that.data.shopImgs[0],
      province: that.data.selProvince,
      city: that.data.selCity,
      county: that.data.selCounty,
      address: that.data.address
    }
    wx.request({
      url: app.globalData.host + '/api/alipay/aliStoreApply',
      data: data,
      success: function (res) {
        if (res.data.Code == 0) {
          utils.showToast('提交成功');
          setTimeout(() => {
            wx.navigateBack({delta: 1})
          }, 1000);
        }else{
          utils.showModal(res.data.Message);
        }
      }
    })
  },

  delOtherPhoto: function (e) {
    let index = e.currentTarget.dataset.index;
    let showOtherPhoto = this.data.showOtherPhoto;
    let otherPhoto = this.data.otherPhoto;
    let newOtherPhoto = [];
    let newShowOtherPhoto = [];
    for(var i = 0;i < otherPhoto.length;i++){
      if(i != index){
        newOtherPhoto.push(otherPhoto[i]);
        newShowOtherPhoto.push(showOtherPhoto[i]);
      }
    }
    this.setData({
      otherPhoto: newOtherPhoto,
      showOtherPhoto: newShowOtherPhoto
    })
  },
 
  // 上传营业执照、身份证正反面、其他证件、门头照、店内照
  uploadLiense: function (e) {
    var that = this;
    let pic = e.currentTarget.dataset.pic;
    that.data.pic = pic;
    var pics = [];
    wx.chooseImage({
      count: 1, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        var imgs = res.tempFilePaths;
        pics.push(imgs[0]);
        that.uploadimgs({
          url: app.globalData.host + '/api/tool/upload?operation=uploadcouponimage', //这里是你图片上传的接口
          path: pics, //这里是选取的图片的地址数组
        });
      },
    })
  },
  uploadimgs: function (data) {
    wx.showLoading({title: '提交中...',mask: true,})
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'fileData',
      formData: null,
      success: (resp) => {
        wx.hideLoading();
        success++;
        let json = JSON.parse(resp.data);
        let pic = parseInt(that.data.pic);
        let imgs = [];
        let showImgs = [];
        imgs.push(json.Data);
        for (let i = 0; i < imgs.length; i++) {
          showImgs[i] = utils.formatAvater(imgs[i], 'https://static.711688.net.cn/upload/coupondetail/');
        }
        switch(pic){
          case 1: that.setData({license: imgs,showLicense: showImgs}); break;   //营业执照
          case 2: that.setData({idCardPosi: imgs,showIdCardPosi: showImgs}); break; //身份证正面
          case 3: that.setData({idCrdRe: imgs,showIdCrdRe: showImgs}); break;   //身份证背面
          case 5: that.setData({headImg: imgs,showHeadImg: showImgs}); break;   //门头照
          case 6: that.setData({shopImgs: imgs,showShopImgs: showImgs}); break; //店内环境
        }
      },
      fail: (res) => {
        fail++;
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用     
          console.log('成功：' + success + " 失败：" + fail);
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimgs(data);
        }
      }
    });
  },

  //上传其他证件
  uploadOtherPhoto: function (e) { //这里是选取图片的方法（其他证件）
    var that = this;
    var pics = that.data.showOtherPhoto;
    let pic = e.currentTarget.dataset.pic;
    that.data.pic = pic;
    if (pics.length >= 6) {
      utils.showToast('最多选择6张！');
      return;
    }
    wx.chooseImage({
      count: 6, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        var imgs = res.tempFilePaths;
        for (var i = 0; i < imgs.length; i++) {
          if (pics.length < 6) {
            pics.push(imgs[i])
          }
        }
        var newsPics = []
        for (var i = 0; i < pics.length; i++) {
          if (pics[i].indexOf("https") == -1) {
            newsPics.push(pics[i])
          }
        }
        if (newsPics.length > 0) {
          that.uploadimgsOther({
            url: app.globalData.host + '/api/tool/upload?operation=uploadcouponimage', 
            path: newsPics, //这里是选取的图片的地址数组
          });
        }
      },
    })
  },
  uploadimgsOther: function (data) {
    wx.showLoading({title: '提交中...',mask: true,})  
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'fileData',
      formData: null,
      success: (resp) => {
        wx.hideLoading();
        success++;
        var str = resp.data
        var pic = JSON.parse(str);
        var pic_name = pic.Data;
        let otherPhoto = that.data.otherPhoto;
        console.log(otherPhoto)
        otherPhoto.push(pic_name);
        let showOtherPhoto = [];
        for (let i = 0; i < otherPhoto.length; i++) {
          showOtherPhoto.push(utils.formatAvater(otherPhoto[i], 'https://static.711688.net.cn/upload/coupondetail/'));
        }
        that.data.otherPhoto = otherPhoto;
        that.setData({
          showOtherPhoto: showOtherPhoto
        })
      },
      fail: (res) => {
        fail++;
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用     
          console.log('成功：' + success + " 失败：" + fail);
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimgsOther(data);
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let tab = options.tab ? options.tab: 1;
    if (options.seltoid) {
      this.setData({
        applyUid: options.seltoid,
        tab:  tab
      });
    }
    
    this.getProvince();
    if(this.data.tab == 1){
      this.getCardApply(this.data.applyUid);      
    }    
    if(this.data.tab == 2){
      this.getAlipay(this.data.applyUid);
    }    
  },

  //申请资料
  getCardApply: function (uid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Coupon/GetCardApply?uid=' + uid,
      success: function (res) {
        if (res.data.Code == 0) {          
          if (res.data.Data) {
            let industry = res.data.Data.Industry ? res.data.Data.Industry : that.data.industry;
            var index = res.data.Data.BankName.indexOf('银行');
            var binkName = index > -1 ? res.data.Data.BankName.substr(0,index + 2) : that.data.binkName
            let imgDomain ='https://static.711688.net.cn/upload/coupondetail/';
            let idCardPosi = [res.data.Data.IdCard]
            let idCrdRe = [res.data.Data.IdCardReverse]
            let license = [res.data.Data.License]           
            let showIdCardPosi = [utils.formatAvater(idCardPosi[0], imgDomain)]
            let showIdCrdRe = [utils.formatAvater(idCrdRe[0], imgDomain)]
            let showLicense = [utils.formatAvater(license[0], imgDomain)]
            let otherPhoto =[];            
            let showOtherPhoto = [];       
            let arrOther = res.data.Data.OtherLicense.split(',');
            for(var i = 0 ;i< arrOther.length; i++){
              if(arrOther[i] != ''){
                otherPhoto.push(arrOther[i]);
                showOtherPhoto.push(utils.formatAvater(arrOther[i], imgDomain))
              }
            }                 
            let applymentMsg = that.getApplyMsg(res.data.Data.PayState,res.data.Data.ApplymentMsg);
            let city = that.data.selCity;
            if(that.data.tab == 1){
              if (res.data.Data.City) {
                city = res.data.Data.City;
                that.getBankList(res.data.Data.City);
              }
            }           
            
            that.setData({
              license: license,//营业执照
              showLicense: showLicense,//渲染营业执照
              idCardPosi: idCardPosi,//身份证正面
              showIdCardPosi: showIdCardPosi,
              idCrdRe: idCrdRe,//身份证背面
              showIdCrdRe: showIdCrdRe,
              otherPhoto: otherPhoto,//其他证件
              showOtherPhoto: showOtherPhoto,
              branchBank: res.data.Data.BankName,
              bankName: binkName,
              bankId: res.data.Data.BankNumber,  
              remark: res.data.Data.Remark,
              payState: res.data.Data.PayState,
              applymentMsg: applymentMsg,
              industry: industry,
              selCity: city,
              adminMobile:  res.data.Data.AdminMobile,
              adminEmail:  res.data.Data.AdminEmail,
              isEditor: true
            })
          }
        }     
      }
    })
  },
  //获取支付宝信息
  getAlipay: function (uid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/alipay/GetAliStoreByUid?uid=' + uid,
      success: function (res) {
        if (res.data.Data && res.data.Data.ext) {
          let ext= JSON.parse(res.data.Data.ext);
          let path = 'https://static.711688.net.cn/upload/coupondetail/';
          let showLicense =  ext.License ? [utils.formatAvater(ext.License, path)] : [];
          let showHeadImg = ext.HeadImg ? [utils.formatAvater(ext.HeadImg, path)] : []; ;
          let showShopImgs = ext.ShopImgs ? [utils.formatAvater(ext.ShopImgs, path)] : []; 
          let applymentMsg = that.getApplyMsg(ext.ApplyState);
          that.setData({
            account: ext.Account,
            name: ext.Name,
            mobile: ext.Mobile,
            email: ext.Email,
            industry: ext.Industry,
            applymentMsg: applymentMsg,
            payState: ext.ApplyState,
            isEditor: ext.ApplyState != 1,
            storeName: ext.StoreName,
            selProvince: ext.Province,
            selCity: ext.City,
            selCounty: ext.County,
            address: ext.Address,
            showLicense: showLicense,   
            showHeadImg: showHeadImg,  
            showShopImgs: showShopImgs,
            license: [ext.License],
            headImg: [ext.HeadImg],
            shopImgs: [ext.ShopImgs],                
          });
        }
      }
    })

  },
  //审核结果
  getApplyMsg: function(state,appendMsg = ''){
    let msg = '';
    if (state == 0) {
      msg = '审核中';
    } else if (state == 1) {
      msg = '已审核';
    } else {
      msg = '已拒绝';
    }
    if (appendMsg) {
      msg += '：' + appendMsg
    }
    return msg;
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    if (app.globalData.userInfo) {
      if (app.globalData.userInfo.Uid != that.data.applyUid) {
        that.setData({
          isSelf: false
        })
      } 
    } else {
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1500)
    }
  }
})